import { Button, Modal, Space, Spin } from "@bytedance/mona-ui"
import dyrequest from "@Utils/request"
import React, { useState } from "react"

import { store } from "~store"
import { setAiCretedList } from "~store/controller/jinritemaiCopyGoods"

import "./index.scss"

let globChangeImage
let setImageTime
function putUpDataFun(data) {
  // console.log('geadUpData', data)
  if (setImageTime) return

  try {
    const { aiCretedList } = store.getState()?.jinritemaiCopyGoods
    let imagesUrls: any = []
    data.forEach((inter, inde) => {
      inter[0] && inter[0].imsdata && imagesUrls.push(...inter[0]?.imsdata)
    })
    if (imagesUrls && imagesUrls.length) {
      if (aiCretedList && aiCretedList.length) {
        const gteInter = JSON.parse(JSON.stringify(aiCretedList))
        gteInter.push(...imagesUrls)
        // aiCretedList.push(...imagesUrls)
        store.dispatch(setAiCretedList(gteInter))
      } else {
        store.dispatch(setAiCretedList(imagesUrls))
      }
    }
  } catch (error) {
    console.log("缓存错误", error)
  }

  // console.log('setImageTime是否关闭', setImageTime)
  globChangeImage && globChangeImage(data)
  setImageTime = setTimeout(() => {
    clearTimeout(setImageTime)
    setImageTime = null
  }, 1000)
}
let iframe
let setAddInfoDatass
let wetsetLodinIframe
function lengthcdata(event) {
  try {
    const putDyImage = JSON.parse(event.data)
    if (putDyImage.type === "putdyimage") {
      putUpDataFun(putDyImage.data)
    }
    if (putDyImage.type === "lodinIframe") {
      wetsetLodinIframe(false)
      // console.log('setAddInfoDatass', setAddInfoDatass)
      setAddInfoDatass.forEach((items, index) => {
        items.forEach((literImage, itous) => {
          literImage.old_url = literImage.url || ""
          // const imgae = literImage.url?.replace('obj/', '')
          // literImage.url = imgae ? imgae + '~110x110_q75.image' : ''
        })
      })
      iframe?.contentWindow.postMessage(
        { type: "dyimage", data: setAddInfoDatass },
        "*"
      )
    }
    if (putDyImage.type === "getHttpFunc") {
      const data = putDyImage.data
      dyrequest(putDyImage.data).then((res) => {
        iframe?.contentWindow.postMessage(
          { type: "putHttpFunc", data: res, id: putDyImage.id },
          "*"
        )
      })
    }
    if (putDyImage.type === "loginStatus") {
      // console.log('登陆状态', putDyImage)
      if (putDyImage.data.status) {
        // console.log('已经登陆')
        Modal.confirm({
          title: "提示",
          content: "是否批量Ai生成图片",
          okText: "是",
          cancelText: "否",
          onOk: (clear) => {
            iframe?.contentWindow.postMessage(
              {
                type: "createAi",
                data: {
                  index: -1
                }
              },
              "*"
            )
            clear()
          }
        })
      }
    }
  } catch (error) {
    // console.log('error', error)
  }
}
function AiOpenImageComp(props: any) {
  // const [addIfameStatus, setAddIfameStatus] = useState(false)
  const [lodinIframe, setLodinIframe] = useState(true)
  wetsetLodinIframe = setLodinIframe
  if (!props) return null
  const {
    type = "",
    visible = false,
    onCancel = () => {},
    setAddInfoData = [],
    product_id,
    img_format = 1,
    onChangeImage = null
  } = props
  globChangeImage = onChangeImage
  let { userShopId = "" } = store.getState().jinritemaiShops
  setAddInfoDatass = setAddInfoData
  const [iframeFoerm, setIframeFoer] = useState<any>(null)

  function clearBox() {
    if (setImageTime) return
    setImageTime = setTimeout(() => {
      clearTimeout(setImageTime)
      setImageTime = null
    }, 1000)
    Modal.warning({
      title: "提示",
      content: "您还未发布，关闭后将不会保存您的修改，是否确认关闭？",
      okText: "确定",
      cancelText: "取消",
      onOk: (clear) => {
        window.removeEventListener("message", lengthcdata, false)
        setLodinIframe(true)
        onCancel(false)
        clear()
      }
    })
  }
  function addLenten() {
    window.addEventListener("message", lengthcdata)
  }
  return (
    <Modal
      size="small"
      width={1300}
      visible={visible}
      footer={
        <Space>
          <Button
            size="mini"
            type="primary"
            onClick={() => {
              iframeFoerm?.contentWindow.postMessage(
                { type: "getUserData" },
                "*"
              )
            }}>
            发布
          </Button>
          <Button size="mini" onClick={() => clearBox()}>
            关闭
          </Button>
        </Space>
      }
      // onOk={() => {
      //     iframeFoerm?.contentWindow.postMessage({ type: 'getUserData' }, '*')
      // }}
      closable={false}
      // okText="发布"
      // cancelText="关闭"
      bodyStyle={{
        padding: 0
      }}
      wrapClassName="addBodersModal"
      mask={true}
      maskClosable={true}
      onCancel={() => clearBox()}
      destroyOnClose={true}>
      <Spin spinning={lodinIframe}>
        {/* lntelliai.com */}
        <iframe
          src={`https://lntelliai.com/imageAI/imageCopy?s=1&shop_id=${userShopId}&type=${type}&product_id=${product_id}&img_format=${img_format}`}
          id="iframe"
          onLoad={(e) => {
            iframe = e.target
            // if (addLenThenData) return
            setIframeFoer(iframe)
            addLenten()
            // event.data就是传递的值
            // console.log('setAddInfoData', setAddInfoData)
          }}
          style={{
            width: "100%",
            height: "785px"
          }}
          frameBorder="0"></iframe>
      </Spin>
    </Modal>
  )
}
export default AiOpenImageComp
